package com.only.webServer.response;

import com.only.webServer.utils.Utils;
import lombok.Setter;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HttpResponse {
    /**
     * 响应状态
     */
    @Setter
    private HttpStatus httpStatus = HttpStatus.OK;

    /**
     * 响应头
     */
    private Map<String, String> header = new HashMap<>();

    private byte[] body = {};

    {
        header.put("Content-Type", "text/html;charset=UTF-8");
        header.put("Date", new Date().toString());
    }

    /**
     * 设置响应头
     */
    public void setHeader(String key, String value) {
        header.put(key, value);
    }

    /**
     * 设置响应体
     */
    public void setBody(byte[] body) {
        this.body = body;
    }

    public void setBody(String body) {
        this.body = body.getBytes(StandardCharsets.UTF_8);
    }

    public byte[] out() {
        StringBuilder builder = new StringBuilder();
        // 设置响应头
        builder.append("HTTP/1.1 ").append(httpStatus.toString()).append("\n");
        builder.append("server: webServer/0.2\n");
        header.forEach((K, V) -> {
            builder.append(K).append(": ").append(V).append("\n");
        });
        builder.append("\n");

        // 写出到字节数据
        byte[] heads = builder.toString().getBytes(StandardCharsets.UTF_8);
        return Utils.appendArray(heads, body);

    }
}
